package drone.iqgc.common ;

import java.util.Arrays ;
import java.util.Objects ;

import javax.servlet.http.HttpServletRequest ;

import org.aspectj.lang.ProceedingJoinPoint ;
import org.aspectj.lang.annotation.Around ;
import org.aspectj.lang.annotation.Aspect ;
import org.slf4j.Logger ;
import org.slf4j.LoggerFactory ;
import org.springframework.stereotype.Component ;
import org.springframework.web.context.request.RequestContextHolder ;
import org.springframework.web.context.request.ServletRequestAttributes ;

import drone.basis.util.NumberUtil ;
import drone.basis.util.StringUtil ;

@Aspect
@Component
public class LoggerAspect
{

	private static final Logger logger = LoggerFactory.getLogger ( LoggerAspect.class ) ;

	@Around ( "execution(* *..controller..*.*(..))" )
	public Object around (
			ProceedingJoinPoint point
	) throws Throwable
	{

		Long topTime = System.currentTimeMillis ( ) ;
		ServletRequestAttributes servletRequestAttributes = ( ServletRequestAttributes ) RequestContextHolder.getRequestAttributes ( ) ;

		Object object = point.proceed ( ) ;
		Long endTime = System.currentTimeMillis ( ) ;
		String resTime = NumberUtil.transfer ( NumberUtil.div ( endTime.doubleValue ( ) - topTime.doubleValue ( ) , 1000D ) ) ;

		if ( ! Objects.isNull ( servletRequestAttributes ) )
		{
			HttpServletRequest request = servletRequestAttributes.getRequest ( ) ;
			if ( ! Objects.isNull ( request ) )
			{
				String info = " | " + request.getRequestURL ( ) + " | " + request.getMethod ( ) + " | " + request.getRemoteAddr ( ) + " | " + point.getTarget ( ).getClass ( ).getName ( ) + " | " + point.getSignature ( ).getName ( ) + " | "
						+ Arrays.toString ( point.getArgs ( ) ) ;
				logger.info ( StringUtil.pad ( resTime , 6 , ' ' , false ) + " Sec" + info ) ;
			}
		}

		return object ;
	}

}
